﻿



(function ($) {
    var template = null;
    var datasource = null;
    var pagesize = 0;
    var currentUrl = null;
    var currentSendData = null;
    var maxPage = 0;
    var currentPage = 0;
    var jsonData = null;
    var selectRowsJosnResult;
    var selectedRowsData;
    var selectedRowData;
    var columnsData;
    var columnsHandle;
    var reloadDataSource;
    var selectedColumnData;
    var selectedColumnHandle;
    var thisElement;

    var reloadPage;
    var rowChangedColumnsData;
    var rowChangedColumnsDataHandle;


    var refreshCurrentDataSource;



    $.fn.DataList = function (options) {

        var defaultOptions =
            {

                columnsName: null,
                template: null,
                datasource: null,
                type: 'Get',
                dataType: 'Json',
                sendData: null,
                isCache: true,
                isAdd: [false, "添加", "btnAdd"], AddFn: null,
                isEdit: [false, "编辑", "btnEdit"], EditFn: null,
                isDelete: [false, "删除", "btnDelete"],
                isSave: [false, "保存", "btnSave"], SaveFn: null,
                isRefresh: [true, "刷新", "btnRefresh"],
                isCheckAll: true,
                isColumnNameEnable: true,
                pager: null,
                pagesize: 10,
                pageItemSeletedCss: null,
                width: 700,
                height: 0


            }

        var opts = $.extend(defaultOptions, options);

        var getColumnNames = function (columnNameArray) {

            var array = new Array();
            for (var i = 0 ; i < columnNameArray.length; i++) {

                var columnName = columnNameArray[i].substring(2, columnNameArray[i].length - 1);
                array.push(columnNameArray[i].substring(2, columnNameArray[i].length - 1));

            }

            return array;

        }
        //初始化表格的头列
        var InitialTHead = function (element, headColumnName, template) {
            if (opts.isColumnNameEnable) {

                var $headColumns = $('<thead></thead>');


                if (!$('thead', element).html()) {
                    if (headColumnName) {

                        var $appentContent = $("<tr></tr>");
                        if (opts.isCheckAll) {
                            $appentContent = $("<tr><td><input type=\"checkbox\" /></td></td></tr>");

                        }
                        for (var i = 0; i < headColumnName.length; i++) {

                            $appentContent.append("<td>" + headColumnName[i] + "</td>");
                        }

                        $headColumns.append($appentContent);

                    } else {
                        var headRegularExpress = /\$\{[a-zA-Z]+\}/gi;
                        var tempColumnNames = template.match(headRegularExpress);
                        var columnsName = getColumnNames(tempColumnNames);

                        var $tempHeadColumns = $("<tr></tr>");
                        if (opts.isCheckAll) {
                            $tempHeadColumns = $("<tr><td><input type=\"checkbox\" /></td></tr>");

                        }
                        for (var j = 0; j < columnsName.length ; j++) {
                            $tempHeadColumns.append("<td>" + columnsName[j] + "</td>");


                        }
                        $headColumns.append($tempHeadColumns);
                    }
                    element.append($headColumns);
                    if (opts.isCheckAll) {

                        $($("thead tr td input[type='checkbox']:first"), element).click(function () {


                            $($("tbody tr td input[type='checkbox']"), element)
                                         .attr("checked", $(this).is(':checked'));
                            $("input[type='checkbox']:first", $("#" + opts.pager))
                                .attr("checked", $(this).is(':checked'));
                        });


                    }
                }
            }
        }

        //初始化表格内容
        var InitialTBody = function (element, template, datasource) {



            if (opts.isCheckAll) {

                var chekckAllTemplate = "<td><input type=\"checkbox\" /></td>";
                var trRegularExpress = /\s*<td>/;
                var trIndex = opts.template.search(trRegularExpress);
                var str1 = opts.template.substring(0, trIndex)
                var str2 = opts.template.substring(trIndex);

                opts.template = str1 + chekckAllTemplate + str2;


                //alert(chekckAllTemplate);



            }
            template = opts.template;

            var $tbody = $('tbody', element);

            if (datasource.DataSource) {
                $.tmpl(template, datasource.DataSource).appendTo($tbody)
                element.append($tbody);
                jsonData = datasource.DataSource;

            } else {

                currentUrl = opts.datasource;
                if (opts.sendData != null) {
                    currentSendData = opts.sendData + "&" + "page=1&pagesize=" + opts.pagesize;

                } else {
                    currentSendData = "page=1&pagesize=" + opts.pagesize;
                }
                currentPage = 1;
                opts.sendData = currentSendData;

                $.ajax({

                    type: opts.type,
                    url: opts.datasource,
                    data: opts.sendData,
                    cache: opts.isCache,
                    success: function (data) {

                        if (data != null) {
                            if (data.DataSource) {


                                $.tmpl(template, data.DataSource).appendTo($tbody)
                                //  element.append($tbody);
                                InitialPager(element, parseInt(data.RowCount));
                                jsonData = data.DataSource;
                                $("#" + opts.pager).css({ 'width': element.width() + 'px' });
                                $($("tbody tr:last td"), $tbody).css({ 'border-bottom': '' });
                            }
                        } else {
                            InitialPager(element, parseInt(0));

                        }
                    },
                    error: function () {
                        alert('初始化数据连接服务器失败');
                    }
                })

            }

            $("tr td input[type='checkbox']", $tbody).live('click', function () {

                if ($(this).is(':checked')) {

                    var currentRowIndex = $($(this).parent().parent()).index('tr', $tbody);
                    // alert(jsonData[currentRowIndex]);
                    selectedRowData = jsonData[currentRowIndex];
                    // alert(selectedRowData);
                }

            });

            //获取到选中之后的行
            selectedRowsData = function () {

                selectRowsJosnResult = new Array();
                $.each($("tr td input[type='checkbox']", $tbody), function () {

                    if ($(this).is(':checked')) {

                        var currentRowIndex = $($(this).parent().parent()).index('tr', $tbody);
                        // alert(jsonData[currentRowIndex]);
                        selectRowsJosnResult.push(jsonData[currentRowIndex]);
                        // alert(selectedRowData);
                    }
                });

                //return selectJosnResult;
            };
            columnsHandle = function (index) {

                columnsData = new Array();

                for (var i = 0; i < jsonData.length; i++) {

                    columnsData.push(jsonData[i][index]);
                }

            };
            selectedColumnHandle = function (index) {
                selectedColumnData = new Array();
                $.each($("tr td input[type='checkbox']", $tbody), function () {

                    if ($(this).is(':checked')) {

                        var currentRowIndex = $($(this).parent().parent()).index('tr', $tbody);
                        // alert(jsonData[currentRowIndex]);



                        selectedColumnData.push(jsonData[currentRowIndex][index]);
                        // alert(selectedRowData);


                    }
                });


            }
            $('tr', $tbody).live('mouseover', function () {

                $(this).addClass("trHover");
                $(this).siblings().removeClass("trHover");
            });

            $('tr:last td').removeClass();
            $('tr:last td').addClass("lastTdStyle");
            //获取到指定改变或列的数据
            rowChangedColumnsDataHandle = function (index, type) {

                rowChangedColumnsData = new Array();
                var columnData1 = "";
                $("tr", $tbody).each(function () {

                    var $childNode = $("td", $(this)).eq(index);
                    //alert($childNode.html());
                    if (type == "text") {
                        columnData1 = $childNode.text();
                    } else if (type == "src") {
                        columnData1 = $(":first", $childNode).attr("src");

                    } else if (type == "value") {

                        columnData1 = $(":first", $childNode).attr("value");

                    }

                    rowChangedColumnsData.push(columnData1);
                })
            }

        };



        //initial pager
        var InitialPager = function (element, rowCount) {
            $('#' + opts.pager).text("");
            var $leftDiv = $("<span  id=\"leftPageItem\" style=\"float:left\"></span>");
            var $rightDiv = $("<span id=\"rightPageItem\" style=\"float:right; display:inline-block;\"></span>");
            if (opts.isCheckAll) {
                $btnCheckAll = $(" <span><input type=\"checkbox\" />全选</span>");
                $leftDiv.append($btnCheckAll);
                $btnCheckAll.click(function () {


                    $("tr td input[type='checkbox']", element).
                           attr('checked', $("input[type='checkbox']", $(this)).is(':checked'));
                });
            }
            if (opts.isAdd[0]) {

                $btnAdd = $("<span id=\"" + opts.isAdd[2] + "\">" + opts.isAdd[1] + "</span>")
                $leftDiv.append($btnAdd);
                if (opts.AddFn) {

                    $btnAdd.click(opts.AddFn);
                }

            }
            if (opts.isEdit[0]) {

                $btnEdit = $("<span id=\"" + opts.isEdit[2] + "\">" + opts.isEdit[1] + "</span>")
                $leftDiv.append($btnEdit)

                if (opts.EditFn) {
                    $btnEdit.click(function () {
                        opts.EditFn(selectedRowData);


                    })
                }

            }
            if (opts.isDelete[0]) {

                $btnDelete = $("<span id=\"" + opts.isDelete[2] + "\">" + opts.isDelete[1] + "</span>")
                $leftDiv.append($btnDelete)


            }
            if (opts.isRefresh[0]) {
                $btnRefresh = $("<span id=\"" + opts.isRefresh[2] + "\">" + opts.isRefresh[1] + "</span>")
                $leftDiv.append($btnRefresh)
                $btnRefresh.click(function () {

                    refreshCurrentDataSource();
                })

            }
            //刷新当前数据
            refreshCurrentDataSource = function () {
                reloadDataSource(element, currentPage);
                // $btnCheckAll.attr('checked', false);
            }
            if (opts.isSave[0]) {
                $btnSave = $("<span id=\"" + opts.isSave[2] + "\">" + opts.isSave[1] + "</span>")
                $leftDiv.append($btnSave)
                if (opts.SaveFn) {

                    $btnSave.click(opts.SaveFn);
                }


            }
            $("#" + opts.pager).append($leftDiv);
            $("#" + opts.pager).append($rightDiv);

            $tbody = $("tbody", element);
            $rightDiv.Pager({

                container: $tbody,
                pagesize: opts.pagesize,
                refreshDatasource: reloadDataSource1,
                rowCount: rowCount,
                currentPage: currentPage
            });

            //重新加载页数
            reloadPage = function (currentPage, rowCount) {
                $("input[type='checkbox']", $leftDiv).attr("checked", false);
                $rightDiv.ReloadPage(currentPage, rowCount);
            }

        }
        thisElement = $(this);
        //初始化样式

        reloadDataSource1 = function (tbody, page) {


            currentUrl = opts.datasource;

            if (!page) {
                page = currentPage;
            }
            var regPage = /page=\d+/;
            var requestPage = "page=" + page;
            currentSendData = currentSendData.replace(regPage, requestPage);
            currentPage = page;



            opts.sendData = currentSendData;
            $.ajax({

                type: opts.type,
                url: opts.datasource,
                data: currentSendData,
                cache: false,
                success: function (data) {
                    if (data) {
                        if (data.DataSource) {

                            $("tr", tbody).remove();

                            $.tmpl(template, data.DataSource).appendTo($tbody)
                            //  element.append($tbody);
                            jsonData = data.DataSource;

                            //InitialPager(element, data.RowCount);
                            // $("#" + opts.pager).css({ 'width': element.width() + 'px' });

                        }
                    }
                },
                error: function () {
                    alert('连接服务器失败');
                }
            });
        };
        var flag = 0
        //刷新当前页面
        reloadDataSource = function (element, page) {


            /*************未知*******************/
            //if (flag == 1) {

            //    flag = 0;
            //    return;
            //}
            //flag++;

            var $tbody = $('tbody', element);
            currentUrl = opts.datasource;

            if (!page) {
                page = currentPage;
            }

            var regPage = /page=\d+/;

            if (page == $("#maxPager_Pager").text()) {
                var rows = $("tr", $tbody).length;
                var deleteRows = $("tr td:nth-child(1) input[type='checkbox']:checked", $tbody).length;
                // alert(rows+" "+deleteRows)
                if (rows == deleteRows) {

                    page--;
                }
            }
            else if (page > 1 && page < 5) {
                    //page--;
            }



            var requestPage = "page=" + page;
            currentSendData = currentSendData.replace(regPage, requestPage);
            currentPage = page;
            $("tr td:first input[type='checkbox']").attr("checked", false);


            opts.sendData = currentSendData;
            $.ajax({

                type: opts.type,
                url: opts.datasource,
                data: currentSendData,
                cache: false,
                success: function (data) {
                    $("tr", $tbody).remove();

                    if (data) {

                        if (data.DataSource) {



                            $.tmpl(template, data.DataSource).appendTo($tbody)
                            //  element.append($tbody);
                            jsonData = data.DataSource;
                            reloadPage(currentPage, data.RowCount);
                            //InitialPager(element, data.RowCount);

                            //$("#" + opts.pager).css({ 'width': element.width() + 'px' });

                        }
                    }
                },
                error: function () {
                    alert('连接服务器失败');
                }
            });
        };





        //获取到选择当前行的数据

        if (!$.browser.msie) {
            thisElement.append("<tbody></tbody>");
        } else {


        }
        InitialTHead($(this), opts.columnsName, opts.template);
        InitialTBody($(this), opts.template, opts.datasource);
        var InitialCss = function (element) {
            thisElement.addClass("dataList");
            $("#" + opts.pager).addClass("dataPager");


            thisElement.css({ 'width': opts.width + 'px', 'overflow': 'scroll' });


            if (opts.isCheckAll) {
                $('td:first', thisElement).css({ 'width': 8 + 'px' })
            }
            element.attr("cellpadding", "0"); element.attr("cellspacing", "0");


        }
        InitialCss($(this));
        template = opts.template;


    }




    //重新加载数据
    $.fn.Refresh = function (currentPage) {

        refreshCurrentDataSource();
        //refreshCurrentDataSource
        // reloadDataSource($(this), currentPage);


    }

    $.fn.Reload = function (options) {

        var defaultOptions =
            {

                type: 'Get',
                url: null,
                sendData: null,
                datatype: 'json',
                pagesize: 10,
                page: 1

            };
        var reloadOpts = $.extend(defaultOptions, options);


        if (reloadOpts.url) {
            currentUrl = reloadOpts.url;
        }
        if (reloadOpts.sendData) {
            currentSendData = reloadOpts.sendData + "&pagesize=" +
                       reloadOpts.pagesize + "&page=" + reloadOpts.page;
            pagesize = reloadOpts.pagesize;
            currentPage = reloadOpts.page;
        }
        refreshCurrentDataSource();

    };

    //获取到最后选择行的数据
    $.fn.SelectedRowData = function () {

        return selectedRowData;
        //  return 
    }

    //获取到选中行的数据，返回一个数组
    $.fn.SeletedRowsData = function () {
        selectedRowData = null;
        selectedRowsData();
        return selectRowsJosnResult
    };
    //获取到指定名称的所有列的值
    $.fn.ColumnData = function (index) {
        columnsData = null;
        columnsHandle(index);

        return columnsData;
    }
    //获取到选择行指定列的数据
    $.fn.SelectedColumnData = function (index) {
        selectedRowData = null;
        selectedColumnHandle(index);
        return selectedColumnData;

    }
    //获取到表格中指定列的内容
    $.fn.RowChangedColumnData = function (index, type) {
        if (!type) {

            type = "text";
        }

        rowChangedColumnsData = null;
        rowChangedColumnsDataHandle(index, type);
        return rowChangedColumnsData;

    }


    //删除数据
    $.fn.Delete = function (options) {

        var defaultOption =
            {
                type: 'Get',
                url: '',
                sendData: null,
                datatype: 'Json'


            }
        var deleteOpts = $.extend(defaultOption, options);
        var deleteRows = function () {

            var sendDataReg = /^\w+=\w+/;
            if (!sendDataReg.test(deleteOpts.sendData)) {
                return;
            }
            if (deleteOpts.url != null && deleteOpts.sendData != null) {
                $.ajax({

                    type: deleteOpts.type,
                    url: deleteOpts.url,
                    datatype: deleteOpts.datatype,
                    data: deleteOpts.sendData,
                    success: function () {

                        thisElement.Refresh();
                        $($("thead tr td input[type='checkbox']:first"), thisElement).
                            attr("checked", false);

                    },
                    error: function () {
                        alert("delete datasource failture , cann't connect servise");
                    }


                });
            }
            //获取到选择之后的行，进行删除
        };

        deleteRows();

    }
    //追加数据

})(jQuery)